package com.haruhinav.controller;


import com.haruhinav.Utils.Constants;
import com.haruhinav.Utils.JWTUtils;
import com.haruhinav.Utils.SearchUtil;
import com.haruhinav.entity.StartNav;
import com.haruhinav.entity.StartNote;
import com.haruhinav.entity.vo.ResultVO;
import com.haruhinav.service.StartNavService;
import com.haruhinav.service.StartNoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * haruhi起始页相关
 *
 *
 */
@RestController
@RequestMapping("/api/start")
public class StartController {

    @Autowired
    private StartNavService startNavService;

    @Autowired
    private StartNoteService startNoteService;


    /**
     * 搜索提示接口
     * @param engine
     * @param keyWord
     * @return
     * @throws IOException
     */
    @GetMapping("/e/tips")
    public ResultVO search(@RequestParam("engine") String engine,@RequestParam(value = "wd",required = false) String keyWord) throws IOException {
        if(ObjectUtils.isEmpty(keyWord)){
            return ResultVO.warning(-1,"参数错误");
        }
        URL url = SearchUtil.selectUrl(engine,keyWord);
        if(null == url){
            return ResultVO.fail(-3,"错误",null);
        }
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestMethod("GET");

        // 接收数据
        InputStream inputStream = httpURLConnection.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while (true) {
            len = inputStream.read(b);
            if (len == -1) {
                break;
            }
            byteArrayOutputStream.write(b, 0, len);
        }
        // java垃圾回收 不需要手动关闭
        byteArrayOutputStream.close();
        return ResultVO.success("OK",byteArrayOutputStream.toString());
    }

    /**
     * 获取用户nav
     * @param id
     * @return
     */
    @GetMapping("/e/navs")
    public ResultVO getStartNav(@RequestParam("userId") Integer id){
        if(ObjectUtils.isEmpty(id)){
            return ResultVO.fail("参数错误");
        }
        List<StartNav> startNavs = startNavService.getListByUser(id);

        return ResultVO.success(startNavs);
    }

    /**
     * 获取默认
     * @return
     */
    @GetMapping("/e/navs/default")
    public ResultVO getDefaultNavs(){
        return ResultVO.success(startNavService.getDefaultNavs());
    }

    /**
     * 修改by user and createTime
     * 注意:这个nav里的userid不是start_nav表里的userid
     * 而是前端从localstory里面获取其的
     * 该接口必须用户登录状态才能获取
     * 但是并无token拦截
     * @param nav
     * @return
     */
    @PostMapping("/e/navs/update")
    public ResultVO updateNavByUser(@RequestBody StartNav nav){

        if(null == nav || ObjectUtils.isEmpty(nav.getUserId()) || ObjectUtils.isEmpty(nav.getTitle()) || ObjectUtils.isEmpty(nav.getUrl())){
            return ResultVO.fail("参数错误");
        }
        return ResultVO.success("修改成功",startNavService.updateNavByUser(nav));
    }

    /**
     * 添加
     * @param nav
     * @return
     */
    @PostMapping("/e/navs/add")
    public ResultVO addNav(@RequestBody StartNav nav){
        if(null == nav || ObjectUtils.isEmpty(nav.getUserId()) || ObjectUtils.isEmpty(nav.getTitle()) || ObjectUtils.isEmpty(nav.getUrl())){
            return ResultVO.fail("参数错误");
        }
        return ResultVO.success("添加成功",startNavService.addNav(nav));

    }

    /**
     * 删除
     * by : uid;timestamp
     * @param nav
     * @return
     */
    @PostMapping("/e/navs/del")
    public ResultVO delNav(@RequestBody StartNav nav){
        if(null == nav|| ObjectUtils.isEmpty(nav.getUserId()) || ObjectUtils.isEmpty(nav.getCreateTime())){
            return ResultVO.fail("参数错误");
        }
        return ResultVO.success("删除成功",startNavService.delNavByUser(nav));
    }

    /**
     * 根据用户获取便签
     * @param userId
     * @return
     */
    @GetMapping("/e/note/{userId}")
    public ResultVO getNoteByUser(@PathVariable Integer userId){
        if(ObjectUtils.isEmpty(userId)){
            return ResultVO.fail("参数错误");
        }
        StartNote startNote = new StartNote();
        startNote.setUserId(userId);
        return ResultVO.success(startNoteService.getListByUser(startNote));
    }

    /**
     * 添加便签
     * @return
     */
    @PostMapping("/e/note/add")
    public ResultVO addNote(@RequestBody StartNote note){
        if(null == note || ObjectUtils.isEmpty(note.getUserId()) || ObjectUtils.isEmpty(note.getTimestamp()) || ObjectUtils.isEmpty(note.getDatetime())){
            return ResultVO.fail("参数错误");
        }
        if(startNoteService.addNote(note) == 0){
            return ResultVO.fail("添加失败");
        }
        return ResultVO.success("添加成功");
    }

    /**
     * 添加或者修改
     * @return
     */
    @PostMapping("/e/note/change")
    public ResultVO noteChange(@RequestBody StartNote note){
        if(null== note || ObjectUtils.isEmpty(note.getUserId())||ObjectUtils.isEmpty(note.getTimestamp())){
            return ResultVO.fail("参数错误");
        }
        List<StartNote> findNote = startNoteService.getListByUser(note);
        int i = 0;
        if(null != findNote){
            if(findNote.size() == 1){
                // 执行修改
                i = startNoteService.update(note);
            }else if (findNote.size() == 0){
                // 执行添加
                i = startNoteService.addNote(note);
            }
        }

        return ResultVO.success("OK",i);
    }

    /**
     * 删除
     * @param note
     * @return
     */
    @PostMapping("/e/note/del")
    public ResultVO delNote(@RequestBody StartNote note){
        if(null== note || ObjectUtils.isEmpty(note.getUserId())||ObjectUtils.isEmpty(note.getTimestamp())){
            return ResultVO.fail("参数错误");
        }
        return ResultVO.success("OK",startNoteService.delByUser(note));
    }
}
